<!-- 范本管理 -->
<template>
    <div>
        <el-form :model="typeForm" :inline="true">
            <el-form-item label="范本名称：" prop="templateName">
			  	 <el-input v-model.trim="typeForm.templateName" ></el-input>
			</el-form-item>
    	    <el-form-item label="合同类型：">
			  	 <el-select  v-model.trim="typeForm.contractType" placeholder="请选择合同类型" >
                    <el-option label="全部" value=""></el-option>
                    <el-option v-for="(type,index) in typOptions" :key="index" :label="type.name" :value="type.code"> </el-option>
                </el-select>
			</el-form-item>
            <el-form-item style="text-align:center" >
				<el-button type="primary"  @click="query(1)" id="monitorEnter">查询</el-button>
                <el-button type="primary"  @click="viewList('add')">新增</el-button>
			</el-form-item>
        </el-form>
        <table-list
        :tableData='tableData'
        :tableLabels='tableLabels'
        :tableProps='tableProps'
        :tableChangeBtns='tableChangeBtns'
        :activeBtn ='tableBtnRule'
        :hasSera='true'
        >
        </table-list>

        <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top:30px"
            :current-page.sync="pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="totalSize">
        </el-pagination>

        <!-- 作废弹框 -->
		<el-dialog
		  :visible.sync="voidDialogVisible"
		  width="30%"
          :show-close="false"
		  center>
            <el-form :model="reasonForm" ref="reasonForm" :rules="rules" :inline="true">
                <el-form-item label="作废原因：" prop="reason" >
                    <el-input
                        type="textarea"
                        :rows="6"
                        placeholder="请输入内容"
                        style="width:calc(30vw - 160px)"
                        v-model.trim="reasonForm.reason">
                    </el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary"  @click="toStop">确定</el-button>
                <el-button type="primary"  @click="voidDialogVisible = false">取消</el-button>
            </span>
		</el-dialog>
    </div>
</template>
<script>
import api from '@/api/apiPath'
import tableList from '../common/tableList'
export default {
    name: 'contractModelManage',
    title: '范本管理',
    components: {'table-list':tableList},
	data () {
		return {
            typeForm:{},
            typOptions:[],
            tableProps:['templateName','templateCode','contractTypeName','statusName','updateTime','updateName','changeBtn'],
            tableLabels:['范本名称'    ,'范本编号'      ,'合同类型'         ,'状态'       ,'更新时间'   ,'更新人'     ,'操作' ],
            tableChangeBtns:[
                {label:"启用",type:'start',fn:this.startList},
                {label:"作废",type:'stop',fn:this.stopList},
                {label:"编辑",type:'edit',fn:this.viewList},
                {label:"详情",type:'view',fn:this.viewList},
                {label:"下载",type:'dowLoad',fn:this.dowLoad},
                {label:"PDF预览",type:'PDF',fn:this.viewPDF},
                {label:"删除",type:'dele',fn:this.deleList}
                ],
            rules:{
                reason:[
                     {required: true, trigger: ['blur', 'change'] ,validator: (rule, value, callback) => {
                            if (!value) {
                                    return callback(new Error('请输入作废原因'));
                            }
                            if(value.length>50){
                                    return callback(new Error('作废原因长度不能大于50'));
                            }
                            callback();
                        }
                    }
                ]
            },
            tableData:[],
            searcName:"",
            pageNum: 1,
            pageSize: 10,//每页几条
            totalSize: 0,

            operateReason:"",//作废原因
            voidDialogVisible:false,
            stopListInfo:{},
            reasonForm:{},
        }
    },
    methods:{
        handleClick(){},
        //新增查看编辑
        viewList(type,idx){
            let id;
            if(type != 'add'){
                id = this.tableData[idx].id
            }
            this.$router.push({path: '/changeContractModel', query: {pageType:type,id:id,typOptions:this.typOptions}})
        },
        //启用
        startList(type,idx){
            this.$confirm(`确定要启用这份范本吗？`, '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.changeStatus(type,idx);
            }).catch(() => {
            });
        },
        //作废
        stopList(type,idx){
            this.voidDialogVisible = true;
            this.stopListIdx = idx;
        },
        toStop(){
            this.$refs.reasonForm.validate((valid)=>{
                if(!valid){
                        return false;
                }
                this.changeStatus('stop',this.stopListIdx)
            })
        },
        //更改范本状态
        changeStatus(type,idx){
            let id = this.tableData[idx].id;
            let status = type == 'start'?1:0;
            let message = type == 'start'?'已启用':'已作废';
            let statusName = type == 'start'?'已启用':'未启用';

            this.axios.post(`${api.UPDATETEMPLATELIST}?id=${id}&status=${status}&reason=${this.reasonForm.reason}`).then(res => {
                if (res.data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: message,
                    });
                    this.tableData[idx].status = status;
                    this.tableData[idx].statusName = statusName;
                    this.voidDialogVisible = false;
                    if(this.reasonForm.reason){
                        this.reasonForm.reason = '';
                        this.$refs.reasonForm.resetFields();
                    }
                    this.searchList();
                }
            })
        },

        //删除
        deleList(type,idx){
            let id = this.tableData[idx].id;
            this.$confirm(`确定要删除当前列表吗？`, '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.axios.post(`${api.DELETEMPLATELIST}?id=${id}`).then(res => {
                    if (res.data.code == 200) {
                        this.tableData.splice(idx,1)
                        this.searchList();
                        this.$message({
                            type: 'success',
                            message: '已删除',
                        });
                    }
                })
            }).catch(() => {
            });
        },
        //下载word文件
        dowLoad(type,idx){
            const upType = ['doc','docx']
            let url = this.tableData[idx].templateEnclosure || '';
            if(url && upType.includes(url.substring(url.lastIndexOf('.') + 1, url.length)) ){
                 this.$message({
                    type: 'info',
                    message: '文件已开始下载',
                });
                window.location=url;
            }else{
                this.$message({
                    type: 'info',
                    message: '文件格式不正确',
                });
            }

        },
        //预览PDF
        viewPDF(type,idx){
            let url = this.tableData[idx].templateEnclosure;
            if(url.substring(url.lastIndexOf('.') + 1, url.length) == 'pdf'){
               window.open(templateEnclosure);
            }
            this.$alert("暂不支持预览word文档", '提示', {
                confirmButtonText: '确定',
                callback: action => {
                }
            });
        },
        query(pageNum){
            let param = {
                pageNum:pageNum||this.pageNum,
                pageSize:this.pageSize,
                templateName:this.typeForm.templateName,
                contractType:this.typeForm.contractType
            };
            this.searchList(pageNum);
        },
        searchList(pageNum){
            let param = {
                pageNum:pageNum||this.pageNum,
                pageSize:this.pageSize,
                templateName:this.typeForm.templateName,
                contractType:this.typeForm.contractType
            };

            this.axios.post(api.GETTEMPLATElIST, param).then(res => {
                if (res.data.code == 200) {
                    let list = res.data.data.list || [];
                    list.forEach(function (item,index,arr) {
                        if(item.status == '1') item.statusName = '已启用'
                        if(item.status == '0') item.statusName = '未启用'
                    });
                    this.tableData = list;
                    this.totalSize = res.data.data.total;
                }
            })

        },
        //新增
        add(){
            this.$router.push({path: '/changeContractModel', query: {pageType:'add'}})
        },

        handleCurrentChange () {
            this.searchList()
		},
		handleSizeChange (val) {
			this.pageSize = val
			this.searchList(1)
        },
        //加载合同类型
        loadTypeList(){
            this.axios.get(api.INITCONTRACTTYPE).then(res => {
                if (res.data.code == 200) {
                    this.typOptions = res.data.data;

                }
            })
        },
        //按钮显示规则
        tableBtnRule(rowData,btns){
            let [...newbtn] = btns;
            if(rowData.status == '1') {
                newbtn.shift();
                newbtn[1].disabled = true;
                newbtn[5].disabled = true;
            }else{
                newbtn.splice(1,1);
                newbtn[1].disabled = false;
                newbtn[5].disabled = false;
            }
            if(rowData.templateEnclosure && rowData.templateEnclosure.lastIndexOf('.') !== 'pdf'){
                 newbtn[4].disabled = true;
            }else{
                newbtn[4].disabled = false;
            }
            return newbtn;
        },

	},
	created () {
        this.searchList()
        this.loadTypeList();
    },
    computed:{

    },
	destroyed() {

	},
	filters: {

	}
}

</script>

<style lang="stylus" scoped>


</style>
